/*****************************************************************************
 * mqtt_paho.c
 *
 * Copyright (C) 2020 Jeasonvor 1101627719@qq.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 ****************************************************************************/

/*****************************************************************************
 * Included Files
 ****************************************************************************/
#include "plum_api.h"
#include "cal/mqtt/plum_mqtt.h"
#include "cal/mqtt/mqtt_paho/paho.mqtt.c/src/MQTTClient.h"
/*****************************************************************************
 * Trace Definitions
 ****************************************************************************/
#define LOG_RUN_LEVEL LOG_LEVEL_DEBUG
#define LOG_MODULE    "mqtt.paho"
#include "thirdparty/log/log.h"
/*****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/*****************************************************************************
 * Private Types
 ****************************************************************************/

/*****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

typedef struct {
    plum_mqtt_drv_read  drv_read;
    plum_mqtt_drv_write drv_write;
    plum_mqtt_cb        app_notice;
    plum_bit            inited;
} mqtt_paho_hdl_t;

/*****************************************************************************
 * Private Data
 ****************************************************************************/
PLUM_PRIVATE mqtt_paho_hdl_t mqtt_hdl;

/*****************************************************************************
 * Public Data
 ****************************************************************************/

/*****************************************************************************
 * Private Functions
 ****************************************************************************/

PLUM_PRIVATE
plum_s32 mqtt_paho_messageArrived(plum_void *context, plum_s8 *topicName,
                                  plum_u32 topicLen, MQTTClient_message *m)
{
    plum_mqtt_msg_t msg = {0};
    msg.topic           = topicName;
    msg.payload         = m->payload;
    msg.payloadLen      = m->payloadlen;

    if (mqtt_hdl.inited && mqtt_hdl.app_notice) {
        mqtt_hdl.app_notice(MQTT_EVT_MSG, &msg);
    }

    return (PLUM_ECODE_OK);
}

/*****************************************************************************
 * Public Functions
 ****************************************************************************/

PLUM_PUBLIC
plum_mqtt_client_ref_t plum_cal_mqtt_connect(plum_s8 *client_id, plum_s8 *url,
                                             plum_u32 port, plum_s8 *usr,
                                             plum_s8 *passwd)
{
    MQTTClient client = plum_null;

    do {
        if (!client_id) {
            LOG_E("client ID is null");
            break;
        }

        if (!url || (port == 0)) {
            LOG_E("mqtt broker is invalid");
            break;
        }

        if (!mqtt_hdl.inited) {
            MQTTClient_init_options option =
                MQTTClient_init_options_initializer;
            MQTTClient_global_init(&option);
            mqtt_hdl.inited = plum_true;
        }

        char addr[128] = {0};
        snprintf(addr, sizeof(addr), "%s:%d", url, port);
        plum_s32 rc = MQTTClient_create(&client, addr, client_id,
                                        MQTTCLIENT_PERSISTENCE_NONE, NULL);
        if (rc) {
            LOG_E("MQTTClient_create err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }

        rc = MQTTClient_setCallbacks(client, plum_null, plum_null,
                                     mqtt_paho_messageArrived, plum_null);
        if (rc) {
            LOG_E("MQTTClient_setCallbacks err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }

        MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
        opts.keepAliveInterval         = 60;
        opts.username                  = usr;
        opts.password                  = passwd;
        opts.MQTTVersion               = MQTTVERSION_DEFAULT;
        rc                             = MQTTClient_connect(client, &opts);
        if (rc) {
            LOG_E("MQTTClient_connect err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }
    } while (0);

    return (client);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_disconnect(plum_mqtt_client_ref_t client)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        if (!client) {
            rc = PLUM_ECODE_INVALID;
            LOG_E("client is invalid,rc: %d", rc);
            break;
        }

        rc = MQTTClient_disconnect(client, 100);
        if (rc) {
            LOG_E("MQTTClient_disconnect err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }

        MQTTClient_destroy(client);
    } while (0);

    return (rc);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_subscribe(plum_mqtt_client_ref_t client, plum_s8 *topic)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        if (!client) {
            rc = PLUM_ECODE_EPARA;
            LOG_E("client ID is null,rc: %d", rc);
            break;
        }

        if (!topic) {
            rc = PLUM_ECODE_INVALID;
            LOG_E("topic is null,rc: %d", rc);
            break;
        }

        rc = MQTTClient_subscribe(client, topic, 1);
        if (rc) {
            LOG_E("MQTTClient_subscribe err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }

    } while (0);

    return (rc);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_unsubscribe(plum_mqtt_client_ref_t client,
                                   plum_s8 *              topic)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        if (!client) {
            rc = PLUM_ECODE_INVALID;
            LOG_E("client is invalid,rc: %d", rc);
            break;
        }

        if (!topic) {
            rc = PLUM_ECODE_EPARA;
            LOG_E("topic pointer is null,rc: %d", rc);
            break;
        }

        rc = MQTTClient_unsubscribe(client, topic);
        if (rc) {
            LOG_E("MQTTClient_unsubscribe err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }
    } while (0);

    return (0);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_publish(plum_mqtt_client_ref_t client,
                               plum_mqtt_msg_t *      msg)
{
    plum_u32 rc = PLUM_ECODE_OK;

    do {
        if (!client) {
            rc = PLUM_ECODE_EPARA;
            LOG_E("client is null,rc: %d", rc);
            break;
        }

        if (!msg) {
            rc = PLUM_ECODE_INVALID;
            LOG_E("msg pointer is null,rc: %d", rc);
            break;
        }

        rc = MQTTClient_publish(client, msg->topic, msg->payloadLen,
                                msg->payload, 1, 0, plum_null);
        if (rc) {
            LOG_E("MQTTClient_publish err,rc: %d", rc);
            rc = PLUM_ECODE_EIO;
            break;
        }
    } while (0);

    return (rc);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_register_callback(plum_mqtt_cb cb)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        if (!cb) {
            rc = PLUM_ECODE_EPARA;
            LOG_E("the application callback is null,rc: %d", rc);
            break;
        }

        mqtt_hdl.app_notice = cb;
    } while (0);

    return (rc);
}

PLUM_PUBLIC
plum_s32 plum_cal_mqtt_register_drv_io(plum_mqtt_drv_read  read,
                                       plum_mqtt_drv_write write)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        if (!read || !write) {
            rc = PLUM_ECODE_INVALID;
            LOG_E("the io callback is null,rc: %d", rc);
            break;
        }

        mqtt_hdl.drv_read  = read;
        mqtt_hdl.drv_write = write;
    } while (0);

    return (rc);
}

PLUM_PUBLIC
plum_void plum_cal_mqtt_yield(plum_void)
{
    MQTTClient_yield();
}
/****************************************************************************/
/*                                                                          */
/*  End of file.                                                            */
/*                                                                          */
/****************************************************************************/
